2
2
.
.
1
1
1
1
.
.
2
2
F
F
r
r
o
o
m
m
R
R
e
e
q
q
u
u
e
e
s
s
t
t
P
P
a
a
r
r
a
a
m
m
e
e
t
t
e
e
r
r
s
s
-
-
U
U
s
s
i
i
n
n
g
g
S
S
e
e
t
t
t
t
e
e
r
r
s
s
-
-
C
C
u
u
s
s
t
t
o
o
m
m
i
i
z
z
e
e
d
d
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to implement Customized Deserialization of HTTP Request Parameters into DTO.
Since this type of Deserialization is done through Setters, you just need to add your custom logic to them.
Also make note that there is no way to map HTTP Request Parameters to DTO Parameters if they have different names.
In this tutorials Request Parameter height uses comma separated value 1,67 which can't automatically loaded into DTO.
Therefore first we load it into String height, replace comma with dot and then convert it into to Float heightFloat Property
Syntax
@RequestMapping("/Hello")
public String hello(PersonDTO personDTO) { ... }
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: Controller Annotations, Tomcat Server
PersonDTO
http://localhost:8080/AddPerson
Tomcat
Browser
MyController
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_deserialize_requestparameters_custom (add Spring Boot Starters from the table)
Create Package: DTO (inside main package)
– Create Class: PersonDTO.java (inside package controllers)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside package controllers)
PersonDTO.java
package com.ivoronline.springboot_deserialize_requestparameters_custom.DTO;
public class PersonDTO {
//PROPERTIES
public String name;
public String height; //"1,67"
public Float heightFloat; // 1.67
//SETTERS (used for deserialization)
public void setName (String name ) { this.name = name; }
public void setHeight (String height) {
height = height.replace(',', '.');
this.heightFloat = Float.parseFloat(height);
}
}
MyController.java
package com.ivoronline.springboot_deserialize_requestparameters_custom.controllers;
import com.ivoronline.springboot_deserialize_requestparameters_custom.DTO.PersonDTO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/AddPerson")
public String addPerson(PersonDTO personDTO) {
return personDTO.name + " is " + personDTO.heightFloat + " meters high";
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
http://localhost:8080/AddPerson?name=John&height=1,67
Application Structure
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>